import {ScrollView, TextInput} from 'react-native-gesture-handler';
import {InputItem, List, Button, WhiteSpace, Provider, PickerView, Modal, Flex, Toast} from '@ant-design/react-native';
import {Image, PermissionsAndroid, Platform, StyleSheet, Text, View, Alert} from 'react-native';
import React, {Component} from 'react';
import {saveParkingRentInfo} from '~/api/parking';
import {getCityListOfOpen, getGeoCity, getPopularCityListOfOpen} from '~/api/public';
import {Geolocation, init, setLocatingWithReGeocode} from 'react-native-amap-geolocation/lib/js';
import Album from '~/pages/home/album/Album';
import {UploadParkingRentFile} from '~/api/upload';
import Spinner from 'react-native-loading-spinner-overlay';

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
    };
};
const seasons = [
    [
        {
            label: '选择方式',
            value: '选择方式',
        },
        {
            label: '出租',
            value: '出租',
        },
        {
            label: '出售',
            value: '出售',
        },
    ],
];
export default class ReleaseParking extends Component {
    static navigationOptions = {
        title: '发布车位',
    };

    constructor(props) {
        super(props);
        this.state = {
            values: undefined,
            visible: false,
            buildingAddress: '',
            buildingName: '',
            contactName: '',
            contactPhone: '',
            parkingName: '',
            areaBuilt: 0,
            areaInner: 0,
            price: 0,
            parkingRentID: 0,
            rentType: 0, // 0出租 1出售
            CityID: 0,
            CityName: '',
            files: [],
            imageid: [],
            spinner: false,
            a: 1,
        };

        //图片上传
        this.onUpload = (files) => {
            this.setState({
                spinner: true,
            });
            UploadParkingRentFile(files)
                .then((r) => {
                    if (r.code === 0) {
                        for (let i = 0; i < r.data.length; i++) {
                            let image = this.state.imageid;
                            image.push(r.data[i].id);
                            this.setState({
                                imageid: image,
                                spinner: false,
                            });
                        }
                    } else {
                        this.setState({
                            spinner: false,
                        });
                        Toast.info('上传失败，原因：' + r.msg, 1);
                    }
                })
                .catch((error) => {
                    console.log(error);
                    this.setState({
                        spinner: false,
                        a: 0,
                    });
                });
        };
        this.onChanges = (values) => {
            this.setState({
                values,
            });
        };
        this.onClose2 = () => {
            this.setState({
                visible: false,
            });
        };
        //热门城市
        getPopularCityListOfOpen().then((r) => {
            if (r.code === 0) {
                // this.props.onSave({
                //     popular_city: r.data,
                // });
            } else {
                alert('获取热门的开放城市失败：' + r.msg);
            }
        });
        getCityListOfOpen().then((r) => {
            if (r.code === 0) {
                let city_list = [];
                let temp_list = [];
                let letter = '';
                r.data.forEach((item) => {
                    if (item.FirstLetter != letter) {
                        if (letter != '') {
                            city_list.push({
                                letter: letter,
                                list: temp_list,
                            });
                        }
                        letter = item.FirstLetter;
                        temp_list = [];
                    }
                    temp_list.push(item);
                });
                city_list.push({
                    letter: letter,
                    list: temp_list,
                });
                // this.props.onSave({
                //     city_list,
                // });
            } else {
                alert('获取开放城市列表失败：' + r.msg);
            }
        });
    }

    async initPostion() {
        // android需要手动获取定位权限
        if (Platform.OS === 'android') {
            await PermissionsAndroid.requestMultiple([
                PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
                PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
            ]);
        }

        // 初始化高德地图SDK
        await init({
            ios: '05e2900e6e7230c91a628709b777b333',
            android: '55322c82dac3b82cb8ddf649e55f5288',
        });

        // 设定iOS获取定位包含逆地理编码
        if (Platform.OS === 'ios') {
            setLocatingWithReGeocode(true);
        }

        this.getLocation();
    }

    getLocation() {
        if (this.props.system.city === '') {
            Geolocation.getCurrentPosition(
                ({location}) => {
                    getGeoCity({city_id: location.adCode}).then((r) => {
                        if (r.code === 0) {
                            let city = location.district || location.city;
                            let city_id = location.adCode;
                            this.setState({
                                CityName: city,
                                CityID: city_id,
                            });
                            // this.props.onSave({
                            //     longitude: location.longitude,
                            //     latitude: location.latitude,
                            //     city,
                            //     city_id,
                            // });
                        } else {
                            Modal.alert('提示', '你所在城市未开放，请手动选择其它开放的城市。', [
                                {
                                    text: '确定',
                                    onPress: () => {
                                        this.onGoCityPage();
                                    },
                                },
                            ]);
                        }
                    });
                },
                (error) => {
                    alert('获取定位失败：' + error.message);
                },
            );
        } else {
            this.setState({
                CityName: this.props.system.city,
                CityID: this.props.system.city_id,
            });
        }
    }

    onGoCityPage = () => {
        this.props.navigation.navigate('City', {
            updateCityName: (CityName, CityID) => {
                this.setState({
                    CityName,
                    CityID,
                });
            },
        });
    };

    setBuildingName = (text) => {
        this.setState({
            buildingName: text,
        });
    };
    setContactName = (text) => {
        this.setState({
            contactName: text,
        });
    };
    setContactPhone = (text) => {
        this.setState({
            contactPhone: text,
        });
    };
    setParkingName = (text) => {
        this.setState({
            parkingName: text,
        });
    };
    setBuildingAddress = (text) => {
        this.setState({
            buildingAddress: text,
        });
    };
    setAreaBuilt = (text) => {
        this.setState({
            areaBuilt: text,
        });
    };
    setAreaInner = (text) => {
        this.setState({
            areaInner: text,
        });
    };
    setPrice = (text) => {
        console.log(text);
        this.setState({
            price: text,
        });
    };

    render() {
        const onsave = () => {
            if (this.state.values == undefined && this.state.values == '选择方式') {
                Toast.info('请选择发布方式', 1);
            } else if (this.state.CityID == 0) {
                Toast.info('请选择城市', 1);
            } else if (this.state.buildingName == '') {
                Toast.info('请输入小区名称', 1);
            } else if (this.state.parkingName == '') {
                Toast.info('请输入车位号', 1);
            } else if (this.state.buildingAddress == '') {
                Toast.info('请输入详细地址', 1);
            } else if (this.state.areaBuilt == 0) {
                Toast.info('请输入建筑面积', 1);
            } else if (this.state.areaInner == 0) {
                Toast.info('请输入使用面积', 1);
            } else if (this.state.price == 0) {
                Toast.info('请输入价格', 1);
            } else if (this.state.contactName == '') {
                Toast.info('请输入姓名', 1);
            } else if (this.state.contactPhone == '') {
                Toast.info('请输入电话', 1);
            } else if (!/^1[3-9]\d{9}$/.test(this.state.contactPhone)) {
                Toast.info('请输入正确的电话号码', 1);
            } else {
                saveParkingRentInfo({
                    AreaBuilt: this.state.areaBuilt,
                    AreaInner: this.state.areaInner,
                    BuildingAddress: this.state.buildingAddress,
                    BuildingName: this.state.buildingName,
                    ContactName: this.state.contactName,
                    ContactPhone: this.state.contactPhone,
                    ParkingName: this.state.parkingName,
                    ParkingRentID: 0,
                    PriceRent: this.state.values == '出租' ? this.state.price : 0,
                    PriceSell: this.state.values == '出售' ? this.state.price : 0,
                    RentType: this.state.values == '出租' ? 0 : this.state.values == '出售' ? 1 : 0,
                    puCityID: this.state.CityID,
                    RelFieldID: this.state.imageid,
                }).then((r) => {
                    if (r.code === 0) {
                        Toast.info('保存成功', 1);
                        this.props.navigation.goBack();
                    } else {
                        Toast.info(r.msg, 1);
                    }
                });
            }
        };
        return (
            <>
                <ScrollView style={styles.scrollview}>
                    <WhiteSpace size="xl" />
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>方式：
                        </Text>
                        <Flex style={{width: '60%', height: 45}} justify="end" align="center">
                            <Text style={{color: '#999999'}} onPress={() => this.setState({visible: true})}>
                                {this.state.values == undefined ? '请选择' : this.state.values}
                            </Text>
                            <Image style={{width: 6.5, height: 12, marginLeft: 15}} source={require('~/assets/info/more.png')} />
                        </Flex>
                        <Modal popup visible={this.state.visible} animationType="slide-up" onClose={this.onClose2}>
                            <View
                                style={{
                                    paddingVertical: 20,
                                    paddingHorizontal: 20,
                                }}>
                                <PickerView onChange={this.onChanges} value={this.state.values} data={seasons} cascade={false} />
                            </View>
                            <Button type="primary" onPress={this.onClose2}>
                                确定
                            </Button>
                        </Modal>
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>获取地址：
                        </Text>
                        <Flex style={{width: '60%', height: 45}} justify="end" align="center">
                            <Text style={{color: '#999999'}} onPress={this.onGoCityPage} numberOfLines={1}>
                                {this.state.CityName == '' ? '选择城市' : this.state.CityName}
                            </Text>
                            <Image style={{width: 6.5, height: 12, marginLeft: 15}} source={require('~/assets/info/more.png')} />
                        </Flex>
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>小区名称：
                        </Text>
                        <TextInput style={styles.inputitem} onChangeText={this.setBuildingName} placeholder="请输入小区" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>车位号：
                        </Text>
                        <TextInput style={styles.inputitem} onChangeText={this.setParkingName} placeholder="请输入车位号" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>详细地址：
                        </Text>
                        <TextInput style={styles.inputitem} onChangeText={this.setBuildingAddress} placeholder="请输入详细地址" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>建筑面积：
                        </Text>
                        <TextInput keyboardType="numeric" style={styles.inputitem} onChangeText={this.setAreaBuilt} placeholder="请输入建筑面积" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>使用面积：
                        </Text>
                        <TextInput keyboardType="numeric" style={styles.inputitem} onChangeText={this.setAreaInner} placeholder="请输入使用面积" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>价格：
                        </Text>
                        <TextInput keyboardType="numeric" style={{width: '53%'}} onChangeText={this.setPrice} placeholder="请输入价格" />
                        {this.state.values == '出租' ? <Text style={{marginLeft: 10}}>元/月</Text> : <Text style={{marginLeft: 10}}>元</Text>}
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>姓名：
                        </Text>
                        <TextInput style={styles.inputitem} onChangeText={this.setContactName} placeholder="请输入姓名" />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    <View style={styles.view}>
                        <Text style={styles.text}>
                            <Text style={{color: 'red'}}>*</Text>电话：
                        </Text>
                        <TextInput
                            maxLength={11}
                            style={styles.inputitem}
                            keyboardType="numeric"
                            onChangeText={this.setContactPhone}
                            placeholder="请输入电话"
                        />
                    </View>
                    <View style={{width: '100%', height: 1, backgroundColor: '#EEEEEE'}}></View>
                    {/*<View style={styles.views}>*/}
                    {/*    <Text style={styles.text}>*/}
                    {/*        <Text style={{color: 'red'}}>*</Text>上传照片：*/}
                    {/*    </Text>*/}
                    {/*    <Spinner visible={this.state.spinner} textContent={'上传中...'} />*/}
                    {/*    <Flex style={{width: '100%', marginTop: 17}} wrap="wrap" justify="center">*/}
                    {/*        <Album*/}
                    {/*            onSelect={(files) => {*/}
                    {/*                this.onUpload(files);*/}
                    {/*            }}*/}
                    {/*            id={0}*/}
                    {/*            spinner={this.state.a === 0 ? 0 : 1}*/}
                    {/*        />*/}
                    {/*    </Flex>*/}
                    {/*</View>*/}
                    <Button style={{marginTop: 15}} type="warning" onPress={onsave}>
                        保存
                    </Button>
                </ScrollView>
            </>
        );
    }
}

const styles = StyleSheet.create({
    scrollview: {
        flex: 1,
        backgroundColor: '#FFFFFF',
    },
    textsize: {
        fontSize: 15,
    },
    inputitem: {
        width: '65%',
    },
    view: {
        width: '100%',
        height: 49,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#FFFFFF',
    },
    imageview: {
        width: 200,
        height: 200,
    },
    text: {
        width: 100,
        marginLeft: 15,
    },
    views: {
        width: '100%',
        flexDirection: 'column',
        marginTop: 17,
    },
});
